package com.kolon.business.mServiceDesk_.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jdom.Document;
import org.jdom.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.kolon.framework.constant.Constant;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.MsgUtil;

@Controller("com.kolon.business.mServiceDesk_.controller.MServiceDeskProcessViewController")
public class MServiceDeskProcessViewController implements SimpleController {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="/business/mServiceDesk_/mServiceDeskProcessView.do")
	public ModelAndView controller(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		// 도메인
		String url = MsgUtil.getMessage("xml.url");
		// 세션 아이디 및 암호 값을 불러옴
		HttpSession httpSession = request.getSession();
		Map userMap = (Map)httpSession.getAttribute(Constant.SESSION_USER_INFO);
		String id = (String)userMap.get("userId");
		String pw = (String)userMap.get("userPw");
		String CR_TYPE = "";	
		String page = ComUtil.nullChk(request.getParameter("page"), "1");
		String tid = id;
		//권한을 새션에 호출
		HttpSession session = request.getSession(true);
		String assignee = (String)session.getAttribute("SESSION_ASSIGNEE");
		String approval = (String)session.getAttribute("SESSION_APPROVAL");
		ModelAndView modelAndView = new ModelAndView();
		//#######################################################################################
		// 처리 현황 저장
		//#######################################################################################
		if("Save".equals(ComUtil.nullChk(request.getParameter("MODE")))) {
			StringBuffer buffer2 = new StringBuffer();
			buffer2.append(url);
			buffer2.append("/servicedesk.aspx?mode=").append("action");
			buffer2.append("&actionMode=").append("2");
			buffer2.append("&ref_num=").append(ComUtil.nullChk(request.getParameter("ref_num")));
			buffer2.append("&cr_type=").append(ComUtil.nullChk(request.getParameter("cr_type")));
			buffer2.append("&cr_company=").append(ComUtil.nullChk(request.getParameter("cr_company")));
			buffer2.append("&cr_pccode=").append(ComUtil.nullChk(request.getParameter("cr_pccode")).split("/")[0]); //요청영역에서 슬러시 뒤에까지 제거
			buffer2.append("&stat_code=").append(ComUtil.nullChk(request.getParameter("stat_code")));
			buffer2.append("&ass_id=").append(ComUtil.nullChk(request.getParameter("ass_id")));
			buffer2.append("&ass_depart=").append(ComUtil.nullChk(request.getParameter("ass_depart")));
			buffer2.append("&priority=").append(ComUtil.nullChk(request.getParameter("priority")));
			buffer2.append("&impact=").append(ComUtil.nullChk(request.getParameter("impact")));
			buffer2.append("&goaldotime=").append(ComUtil.nullChk(request.getParameter("goaldotime")));
			buffer2.append("&symt_code1=").append(ComUtil.nullChk(request.getParameter("symt_code1")));
			buffer2.append("&symt_code=").append(ComUtil.nullChk(request.getParameter("symt_code")));			
			buffer2.append("&rootcause=").append(ComUtil.nullChk(request.getParameter("rootcause")));
			if(ComUtil.nullChk(request.getParameter("cr_type")).equals("I")){
				if (!"".equals(ComUtil.nullChk(request.getParameter("realinopen_date")))) {
					buffer2.append("&realinopen=").append(ComUtil.nullChk(request.getParameter("realinopen_date"))+ "%20" + ComUtil.nullChk(request.getParameter("realinopen_hour"))+ ":" + ComUtil.nullChk(request.getParameter("realinopen_minute")) + ":00");
				} else {
					buffer2.append("&realinopen=").append("");
				}
				if (!"".equals(ComUtil.nullChk(request.getParameter("realinclose_date")))) {
					buffer2.append("&realinclose=").append(ComUtil.nullChk(request.getParameter("realinclose_date"))+ "%20" + ComUtil.nullChk(request.getParameter("realinclose_hour"))+ ":" + ComUtil.nullChk(request.getParameter("realinclose_minute")) + ":00");
				} else {
					buffer2.append("&realinclose=").append("");
				}
			}else{ //REQUEST 경우
				buffer2.append("&realinopen=").append("");
				buffer2.append("&realinclose=").append("");
			}
			buffer2.append("&stat_desc=").append(ComUtil.getEncode(ComUtil.nullChk(request.getParameter("stat_desc")),"EUC-KR"));
			buffer2.append("&incicause=").append(ComUtil.getEncode(ComUtil.nullChk(request.getParameter("incicause")),"EUC-KR"));
			buffer2.append("&dodetail=").append(ComUtil.getEncode(ComUtil.nullChk(request.getParameter("dodetail")),"EUC-KR"));
			buffer2.append("&opinion=").append(ComUtil.getEncode(ComUtil.nullChk(request.getParameter("opinion")),"EUC-KR"));
			buffer2.append("&userid=").append(tid);
			// XML DOCUMENT 및 인증 처리
			ComUtil.getDocument(buffer2.toString(), id, pw);
			modelAndView.addObject("message", "저장되었습니다.");
			modelAndView.addObject("scriptType", "003");
			//modelAndView.addObject("message_url", "/business/mServiceDesk_/mServiceDeskProcessView.do?Ref_Num="+request.getParameter("ref_num")+"&page="+page + "&endY="+request.getParameter("endY"));
			modelAndView.addObject("message_url", "/business/mServiceDesk_/mServiceDeskProcessList.do?Status="+ComUtil.nullChk(request.getParameter("Status"),"ING")+"&page="+page + "&endY="+request.getParameter("endY"));
			modelAndView.setViewName("/business/common/alert");
		//#######################################################################################
		}else{
		//#######################################################################################
		// 인시던트 와 리퀘스트 전환시 cr_type을 변경해줘야함.
			String  Ref_Type = ComUtil.nullChk(request.getParameter("Ref_Type"));
			if (!"".equals(Ref_Type)) {
				StringBuffer sbf = new StringBuffer();
				sbf.append(url);
				sbf.append("/servicedesk.aspx?mode=").append("action");
				sbf.append("&actionMode=").append("2");
				sbf.append("&ref_num=").append(ComUtil.nullChk(request.getParameter("Ref_Num")));
				sbf.append("&cr_type=").append(Ref_Type);
				sbf.append("&userid=").append(tid);
				// XML DOCUMENT 및 인증 처리
				ComUtil.getDocument(sbf.toString(), id, pw);
			}
		StringBuffer buffer = new StringBuffer();
		buffer.append(url);
		Map map = new HashMap();
		String ZC_CODE = ""; //요청영역
		String ASS_DEPART = ""; //처리부서
		//#######################################################################################
		// 처리 상세보기(기본 값)
		//#######################################################################################
		buffer.append("/servicedesk.aspx?mode=").append("5");
		buffer.append("&ref_num=").append(ComUtil.nullChk(request.getParameter("Ref_Num")));
		buffer.append("&userid=").append(tid);
		// XML DOCUMENT 및 인증 처리
		Document doc = ComUtil.getDocument(buffer.toString(), id, pw);
		Element element = doc.getRootElement();
		List xmlList = element.getChildren("Table");
		Iterator itXml = xmlList.iterator();
		// XML 데이터 
		if (itXml.hasNext()) {
			Element el = (Element)itXml.next();
			map = new HashMap();
			CR_TYPE = ComUtil.nullChk(el.getChild("CR_TYPE").getText());
			map.put("REF_NUM", el.getChild("REF_NUM").getText());              //요청번호
			map.put("CR_TYPE", el.getChild("CR_TYPE").getText());              //요청타입 (I : Incident, R: Request)
			map.put("CUSTOMER_INFO", el.getChild("CUSTOMER_INFO").getText());  //요청자			
			map.put("CR_COMPANY", el.getChild("CR_COMPANY").getText());        //요청회사코드
			map.put("CR_PCCODE", el.getChild("CR_PCCODE").getText());          //요청영역코드	
			ZC_CODE = ComUtil.nullChk(el.getChild("CR_COMPANY").getText());
			map.put("CR_DESC", el.getChild("CR_DESC").getText());              //요청내역
			map.put("OPEN_DATE", el.getChild("OPEN_DATE").getText());          //요청일
			map.put("STAT_CODE", el.getChild("STAT_CODE").getText());          //진행상태 
			map.put("PLAN_DATE", el.getChild("PLAN_DATE").getText());          //희망완료일
			map.put("CLOSE_DATE", el.getChild("CLOSE_DATE").getText());        //완료일자
			map.put("ASS_DEPART", el.getChild("ASS_DEPART").getText());        //처리자부서
			ASS_DEPART = el.getChild("ASS_DEPART").getText();
			map.put("ASS_ID", el.getChild("ASS_ID").getText());                //처리자
			map.put("PRIORITY", el.getChild("PRIORITY").getText());            //우선순위
			map.put("IMPACT", el.getChild("IMPACT").getText());                //비즈니스영향도 			
			map.put("GOALDOTIME", el.getChild("GOALDOTIME").getText());        //목표처리시간 
			map.put("SYMT1_DESC", el.getChild("SYMT1_DESC").getText());        //상세분류그룹 
			map.put("SYMT_CODE", el.getChild("SYMT_CODE").getText());          //상세분류 
			map.put("ROOTCAUSE", el.getChild("ROOTCAUSE").getText());          //RootCause  
			map.put("REALINOPEN_DATE", ComUtil.toSubString(el.getChild("REALINOPEN").getText(),0,10));        //실장애 발생시간 
			map.put("REALINOPEN_HOUR", ComUtil.sToi(ComUtil.toSubString(el.getChild("REALINOPEN").getText(),11,13)));        //실장애 발생시간 
			map.put("REALINOPEN_MINUTE", ComUtil.sToi(ComUtil.toSubString(el.getChild("REALINOPEN").getText(),14,16)));        //실장애 발생시간 
			map.put("REALINCLOSE_DATE", ComUtil.toSubString(el.getChild("REALINCLOSE").getText(),0,10));      //실장애 처리시간 			
			map.put("REALINCLOSE_HOUR", ComUtil.sToi(ComUtil.toSubString(el.getChild("REALINCLOSE").getText(),11,13)));      //실장애 처리시간
			map.put("REALINCLOSE_MINUTE", ComUtil.sToi(ComUtil.toSubString(el.getChild("REALINCLOSE").getText(),14,16)));      //실장애 처리시간
			map.put("STAT_DESC", el.getChild("STAT_DESC").getText());          //현재진행내역
			map.put("INCICAUSE", el.getChild("INCICAUSE").getText());          //장애원인 
			map.put("DODETAIL", el.getChild("DODETAIL").getText());            //조치내역
			map.put("OPINION", el.getChild("OPINION").getText());              //추가의견			
			map.put("NABGI_BTN", ComUtil.nullChk(el.getChild("NABGI_BTN").getText())); 		   //납기조정버튼유무(Y:버튼 활성, null:버튼 비활성)
			map.put("ALERT_BTN", ComUtil.nullChk(el.getChild("ALERT_BTN").getText())); 		   //처리계획알림버튼유무(Y:버튼 활성, null:버튼 비활성)
		}	
		//#######################################################################################
		//#######################################################################################
		// 회사 리스트
		//#######################################################################################
		StringBuffer buffer2 = new StringBuffer();
		buffer2.append(url);
		buffer2.append("/servicedesk.aspx?mode=").append("5-1");
		buffer2.append("&userid=").append(tid);
		// XML DOCUMENT 및 인증 처리
		Document doc2 = ComUtil.getDocument(buffer2.toString(), id, pw);
		Element element2 = doc2.getRootElement();
		List xmlList2 = element2.getChildren("Table");
		Iterator itXml2 = xmlList2.iterator();
		List mapList2 = new ArrayList();
		Map map2 = new HashMap();
		// XML 데이터 
		while (itXml2.hasNext()) {
			Element el = (Element)itXml2.next();
			map2 = new HashMap();
			map2.put("ZC_CODE", el.getChild("ZC_CODE").getText());
			map2.put("ZC_NAME", el.getChild("ZC_NAME").getText());
			mapList2.add(map2);
		}		
		//#######################################################################################
		//#######################################################################################
		// 요청 영역 리스트
		//#######################################################################################
		StringBuffer buffer3 = new StringBuffer();
		buffer3.append(url);
		buffer3.append("/servicedesk.aspx?mode=").append("5-2"); //5-2가 영역임
		buffer3.append("&userid=").append(tid);
		buffer3.append("&zc_code=").append(ZC_CODE);
		// XML DOCUMENT 및 인증 처리
		Document doc3 = ComUtil.getDocument(buffer3.toString(), id, pw);
		Element element3 = doc3.getRootElement();
		List xmlList3 = element3.getChildren("Table");
		Iterator itXml3 = xmlList3.iterator();
		List mapList3 = new ArrayList();
		Map map3 = new HashMap();
		// XML 데이터 
		while (itXml3.hasNext()) {
			Element el = (Element)itXml3.next();
			map3 = new HashMap();
			map3.put("PC_CODE", el.getChild("PC_CODE").getText());
			map3.put("PC_NAME", el.getChild("PC_NAME").getText());
			map3.put("PC_PRIORITY", el.getChild("PC_PRIORITY").getText());
			mapList3.add(map3);
		}		
		//#######################################################################################
		//#######################################################################################
		// 처리부서 리스트
		//#######################################################################################
		StringBuffer buffer4 = new StringBuffer();
		buffer4.append(url);
		buffer4.append("/servicedesk.aspx?mode=").append("5-4");
		buffer4.append("&userid=").append(tid);
		// XML DOCUMENT 및 인증 처리
		Document doc4 = ComUtil.getDocument(buffer4.toString(), id, pw);
		Element element4 = doc4.getRootElement();
		List xmlList4 = element4.getChildren("Table");
		Iterator itXml4 = xmlList4.iterator();
		List mapList4 = new ArrayList();
		Map map4 = new HashMap();
		// XML 데이터 
		while (itXml4.hasNext()) {
			Element el = (Element)itXml4.next();
			map4 = new HashMap();
			map4.put("DP_CODE", el.getChild("DP_CODE").getText());
			map4.put("DP_NAME", el.getChild("DP_NAME").getText());
			mapList4.add(map4);
		}		
		//#######################################################################################
		//#######################################################################################
		// 처리자 리스트
		//#######################################################################################
		StringBuffer buffer5 = new StringBuffer();
		buffer5.append(url);
		buffer5.append("/servicedesk.aspx?mode=").append("5-5");
		buffer5.append("&userid=").append(tid);
		buffer5.append("&dp_code=").append(ASS_DEPART);
		// XML DOCUMENT 및 인증 처리
		Document doc5 = ComUtil.getDocument(buffer5.toString(), id, pw);
		Element element5 = doc5.getRootElement();
		List xmlList5 = element5.getChildren("Table");
		Iterator itXml5 = xmlList5.iterator();
		List mapList5 = new ArrayList();
		Map map5 = new HashMap();
		// XML 데이터 
		while (itXml5.hasNext()) {
			Element el = (Element)itXml5.next();
			map5 = new HashMap();
			map5.put("ID", el.getChild("ID").getText());
			map5.put("NAME", el.getChild("NAME").getText());
			mapList5.add(map5);
		}		
		//#######################################################################################
		//#######################################################################################
		// 상세분류
		//#######################################################################################
		StringBuffer buffer6 = new StringBuffer();
		buffer6.append(url);
		buffer6.append("/servicedesk.aspx?mode=").append("5-6");
		buffer6.append("&userid=").append(tid);		
		buffer6.append("&cr_type=").append(CR_TYPE);
		// XML DOCUMENT 및 인증 처리
		Document doc6 = ComUtil.getDocument(buffer6.toString(), id, pw);
		Element element6 = doc6.getRootElement();
		List xmlList6 = element6.getChildren("Table");
		Iterator itXml6 = xmlList6.iterator();
		List mapList6 = new ArrayList();
		Map map6 = new HashMap();
		// XML 데이터 
		while (itXml6.hasNext()) {
			Element el = (Element)itXml6.next();
			map6 = new HashMap();
			map6.put("SYMT1_DESC", el.getChild("SYMT1_DESC").getText());
			//map6.put("NAME", el.getChild("NAME").getText());
			mapList6.add(map6);
		}
		// 상세분류 선택
		List mapList_ = new ArrayList();
		if (map.get("SYMT1_DESC") != null && !"".equals(map.get("SYMT1_DESC"))) {
			StringBuffer buffer_ = new StringBuffer();
			buffer_.append(url);
			buffer_.append("/servicedesk.aspx?mode=").append("5-7");
			buffer_.append("&userid=").append(tid);		
			buffer_.append("&cr_type=").append(CR_TYPE);
			buffer_.append("&symt1_desc=").append(ComUtil.getEncode((String)map.get("SYMT1_DESC"),"EUC-KR"));
			// XML DOCUMENT 및 인증 처리
			Document doc_ = ComUtil.getDocument(buffer_.toString(), id, pw);
			Element element_ = doc_.getRootElement();
			List xmlList_ = element_.getChildren("Table");
			Iterator itXml_ = xmlList_.iterator();
			Map map_ = null;
			// XML 데이터 
			while (itXml_.hasNext()) {
				Element el = (Element)itXml_.next();
				map_ = new HashMap();
				map_.put("SYMT_CODE", el.getChild("SYMT_CODE").getText());
				map_.put("SYMT_DESC", el.getChild("SYMT_DESC").getText());
				mapList_.add(map_);
			}
		}
		//#######################################################################################
		//#######################################################################################
		// 근본원인 (Incident)
		//#######################################################################################
		StringBuffer buffer7 = new StringBuffer();
		buffer7.append(url);
		buffer7.append("/servicedesk.aspx?mode=").append("5-8");
		buffer7.append("&userid=").append(tid);		
		// XML DOCUMENT 및 인증 처리
		Document doc7 = ComUtil.getDocument(buffer7.toString(), id, pw);
		Element element7 = doc7.getRootElement();
		List xmlList7 = element7.getChildren("Table");
		Iterator itXml7 = xmlList7.iterator();
		List mapList7 = new ArrayList();
		Map map7 = new HashMap();
		// XML 데이터 
		while (itXml7.hasNext()) {
			Element el = (Element)itXml7.next();
			map7 = new HashMap();
			map7.put("RC_CODE", el.getChild("RC_CODE").getText());
			map7.put("RC_DESC", el.getChild("RC_DESC").getText());
			mapList7.add(map7);
		}		
		//#######################################################################################
		//#######################################################################################
		// 진행상태
		//#######################################################################################
		StringBuffer buffer8 = new StringBuffer();
		buffer8.append(url);
		buffer8.append("/servicedesk.aspx?mode=").append("5-3");
		buffer8.append("&userid=").append(tid);
		buffer8.append("&cr_type=").append(CR_TYPE);
		// XML DOCUMENT 및 인증 처리
		Document doc8 = ComUtil.getDocument(buffer8.toString(), id, pw);
		Element element8 = doc8.getRootElement();
		List xmlList8 = element8.getChildren("Table");
		Iterator itXml8 = xmlList8.iterator();
		List mapList8 = new ArrayList();
		Map map8 = new HashMap();
		// XML 데이터 
		while (itXml8.hasNext()) {
			Element el = (Element)itXml8.next();
			map8 = new HashMap();
			map8.put("STAT_CODE", el.getChild("STAT_CODE").getText());
			map8.put("STAT_NAME", el.getChild("STAT_NAME").getText());
			mapList8.add(map8);
		}		
		//#######################################################################################
		modelAndView.addObject("viewMap", map); //상세정보 (기본값)
		modelAndView.addObject("mapList2", mapList2); //회사리스트
		modelAndView.addObject("mapList3", mapList3); //요청영역
		modelAndView.addObject("mapList4", mapList4); //처리부서
		modelAndView.addObject("mapList5", mapList5); //처리자
		modelAndView.addObject("mapList6", mapList6); //상세분류
		modelAndView.addObject("mapList_", mapList_); //상세분류 (2차)
		modelAndView.addObject("mapList7", mapList7); //근본원인
		modelAndView.addObject("mapList8", mapList8); //진행상태
		//#######################################################################################
		}
		//#######################################################################################
		modelAndView.addObject("assignee", assignee);
		modelAndView.addObject("approval", approval);
		modelAndView.addObject("page", page);
		String CrType = "";
		String  Ref_Type = ComUtil.nullChk(request.getParameter("Ref_Type"));
		if(Ref_Type.equals("")){ //자동입력시
			//Request Or Incident 처리
			if(CR_TYPE.equals("R")){
				CrType = "R";
			}else if(CR_TYPE.equals("I")){
				CrType = "I";
			}
		}else{ //수동입력시
			if(Ref_Type.equals("R")){
				CrType = "R";
			}else if(Ref_Type.equals("I")){
				CrType = "I";
			}
			
		}
		modelAndView.addObject("Ref_Type", Ref_Type);
		modelAndView.addObject("CrType", CrType);
		modelAndView.addObject("Status", ComUtil.nullChk(request.getParameter("Status"),"ING"));
		return modelAndView;
	}

}